package cn.edu.xmu.orderpayment.payment.Dao;

import cn.edu.xmu.oomall.core.util.ReturnNo;
import cn.edu.xmu.oomall.core.util.ReturnObject;
import cn.edu.xmu.oomall.core.util.Common;
import cn.edu.xmu.orderpayment.payment.mapper.PaymentPatternPoMapper;
import cn.edu.xmu.orderpayment.payment.mapper.PaymentPoMapper;
import cn.edu.xmu.orderpayment.payment.model.bo.Payment;
import cn.edu.xmu.orderpayment.payment.model.bo.PrePayment;
import cn.edu.xmu.orderpayment.payment.model.po.*;
import cn.edu.xmu.orderpayment.payment.model.vo.SimplePayment;
import cn.edu.xmu.orderpayment.payment.model.vo.SimplePaymentRetVo;
import cn.edu.xmu.privilegegateway.annotation.util.RedisUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import static cn.edu.xmu.privilegegateway.annotation.util.Common.setPoCreatedFields;
import static cn.edu.xmu.privilegegateway.annotation.util.Common.setPoModifiedFields;
import static cn.edu.xmu.privilegegateway.annotation.util.Common.cloneVo;

/**
 * @author Guanlin Wang 22920192204282
 * @date 2021/12/12
 * Dao层只用来对数据库做增删查改
 */
@Repository
public class PaymentDao {
    private static final Logger logger = LoggerFactory.getLogger(PaymentDao.class);

    @Autowired(required = false)
    PaymentPoMapper paymentPoMapper;

    @Autowired(required = false)
    PaymentPatternPoMapper paymentPatternPoMapper;

    /**
     * 顾客支付订单
     * @param payment
     * @return
     */
    public ReturnObject createPayment(Payment payment) {
        try{
            PaymentPo po=cloneVo(payment,PaymentPo.class);
            paymentPoMapper.insertSelective(po);
            Payment payment1=cloneVo(po,Payment.class);
            return new ReturnObject<>(payment1);
        }catch (Exception e){
            logger.error(e.getMessage());
            return new ReturnObject(ReturnNo.INTERNAL_SERVER_ERR,e.getMessage());
        }
    }

//    /**
//     * 平台管理员查询支付单信息详情
//     * 查询条件：支付单ID
//     * 不返回已被逻辑删除的支付单信息
//     *
//     * 利用Mapper的select和PoExample配合
//     * @return Payment
//     */
//    public ReturnObject getPaymentDetailInfo(Long id) {
//        try {
//            PaymentPo paymentPo = paymentPoMapper.selectByPrimaryKey(id);
//            if (paymentPo == null) {
//                return new ReturnObject(ReturnNo.RESOURCE_ID_NOTEXIST, "支付信息不存在");
//            }
//            Payment payment = cloneVo(paymentPo, Payment.class);
//            return new ReturnObject(payment);
//        } catch (Exception e) {
//            return new ReturnObject(ReturnNo.INTERNAL_SERVER_ERR, e.getMessage());
//        }
//    }

    /**
     * 通过母单id找到支付单信息
     * @param pid
     * @return
     */
    public ReturnObject getPaymentById(Long pid) {
        try{
            PaymentPo po=  paymentPoMapper.selectByPrimaryKey(pid);
            if(po == null)
                return new ReturnObject(ReturnNo.RESOURCE_ID_NOTEXIST,"该支付单不存在");
            Payment payment = cloneVo(po,Payment.class);
            return new ReturnObject<>(payment);
        }catch (Exception e){
            logger.error(e.getMessage());
            return new ReturnObject(ReturnNo.INTERNAL_SERVER_ERR,e.getMessage());
        }
    }

    /**
     * 平台管理员查询支付信息
     * 查询条件：单据ID，状态，晚于此支付时间，早于此支付时间，页码，页数
     * 不返回已被逻辑删除的支付信息，按照时间倒序
     *
     * 利用Mapper的select和PoExample配合
     * @return Array(SimplePayment)
     */
    public ReturnObject getPaymentInfo(PaymentPoExample example, Integer page,Integer pageSize) {

        try {
            PageHelper.startPage(page, pageSize);
            List<PaymentPo> poList = paymentPoMapper.selectByExample(example);
            List<SimplePaymentRetVo> simplePaymentRetVoList = new ArrayList<>();
            for (PaymentPo paymentPo : poList) {
                simplePaymentRetVoList.add( cloneVo(paymentPo,SimplePaymentRetVo.class));
            }

            PageInfo pageInfo = PageInfo.of(poList);
            pageInfo.setList(simplePaymentRetVoList);
            return new ReturnObject(pageInfo);

        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ReturnObject(ReturnNo.INTERNAL_SERVER_ERR, e.getMessage());
        }
    }

    /**
     * 通过支付id查询详细信息
     * @param id
     * @return
     */
    public ReturnObject selectPaymentInfoByPrimaryKey(Long id){
        try{
            PaymentPo po = paymentPoMapper.selectByPrimaryKey(id);
            ReturnObject ret = new ReturnObject(po);
            return Common.getRetVo(ret, Payment.class);
        }catch (Exception e){
            logger.error(e.getMessage());
            return new ReturnObject(ReturnNo.INTERNAL_SERVER_ERR, e.getMessage());
        }
    }


    /**
     * 更新信息, 对数据库进行操作
     * @param bo
     * @param loginUserId
     * @param loginUserName
     * @return
     */
    public ReturnObject updatePayment(Payment bo, Long loginUserId, String loginUserName) {
        try{
            PaymentPo po = paymentPoMapper.selectByPrimaryKey(bo.getId());//通过id创建Payment的PO对象
            if(po == null)
                return new ReturnObject(ReturnNo.RESOURCE_ID_NOTEXIST, "退款id不存在");
            Payment retBo = (Payment)cloneVo(po, Payment.class);// 模型转换
            ///只有未对账的状态才能修改，用于手工挂账处理，否则出507错误
//            if(po.getState().equals(Payment.State.RECONCILIATION_COMPLETED.getCode()) || po.getState().equals(Payment.State.LIQUIDATION_COMPLETED.getCode())){
//                return new ReturnObject(ReturnNo.STATENOTALLOW,"当前状态禁止此操作");// 为什么不在业务逻辑层校验该退款单的状态是否为 ReturnNo.STATENOTALLOW?
//            }
            po.setState(bo.getState().getCode());// 校验无误后设置状态
            if(bo.getDescr() != null)
                po.setDescr(bo.getDescr());
            //根据传入的body修改信息
            setPoModifiedFields(po, loginUserId, loginUserName);
            paymentPoMapper.updateByPrimaryKeySelective(po);//通过
            return new ReturnObject(retBo);
        }catch (Exception e){
            logger.error(e.getMessage());
            return new ReturnObject(ReturnNo.INTERNAL_SERVER_ERR, e.getMessage());
        }
    }

    /**
     * 根据订单id查询支付信息
     * @param example
     * @param voClass
     * @return
     */
    public ReturnObject customerSelectPaymentInfoByExample(PaymentPoExample example, Class voClass) {
        try{
            List<PaymentPo> pos = paymentPoMapper.selectByExample(example);
            PageInfo paymentPoPageInfo = new PageInfo(pos);
            ReturnObject returnObject = Common.getPageRetVo(new ReturnObject<>(paymentPoPageInfo), voClass);
            return returnObject;
        }catch (Exception e){
            logger.error(e.getMessage());
            return new ReturnObject(ReturnNo.INTERNAL_SERVER_ERR, e.getMessage());
        }
    }

    /**
     * 顾客查询支付信息
     * 返回信息包一个SimplePayment类型的对象
     * @param documentId 单据id
     * @return
     */
    public ReturnObject customerSelectPayment(String documentId) {
        PaymentPoExample example = new PaymentPoExample();
        PaymentPoExample.Criteria criteria = example.createCriteria();
        if (documentId != null)
            criteria.andDocumentIdEqualTo(documentId);
        ReturnObject ret = customerSelectPaymentInfoByExample(example, SimplePayment.class);
        return ret;
    }

//    /**
//     * 平台管理员修改支付单信息
//     * @return
//     */
//    public ReturnObject modifyPaymentInfo(Payment paymentBo, Long loginId, String loginName) {
//        try {
//            PaymentPo paymentPo = cloneVo(paymentBo, PaymentPo.class);
//            setPoModifiedFields(paymentPo, loginId, loginName);
//            paymentPoMapper.updateByPrimaryKeySelective(paymentPo);
//            return new ReturnObject(paymentPoMapper.selectByPrimaryKey(paymentBo.getId()));
//        } catch (Exception e) {
//            logger.error("PayDao.modifyPaymentInfo:" + e.getMessage());
//            return new ReturnObject(ReturnNo.INTERNAL_SERVER_ERR, e.getMessage());
//        }
//    }

//    /**
//     * 修改支付单为已对账
//     * @param payment
//     * @return
//     */
//    public ReturnObject setPaymentReconciled(Payment payment){
//        try{
//            PaymentPo paymentPo = cloneVo(payment, PaymentPo.class);
//            paymentPoMapper.updateByPrimaryKeySelective(paymentPo);
//            return new ReturnObject(ReturnNo.OK);
//        }catch (Exception e){
//            logger.error(e.getMessage());
//            return new ReturnObject(ReturnNo.INTERNAL_SERVER_ERR,e.getMessage());
//        }
//    }

    public ReturnObject<List> getPaymentByDocumentId(String documentId) {
        try {
            PaymentPoExample example = new PaymentPoExample();
            PaymentPoExample.Criteria criteria = example.createCriteria();
            criteria.andDocumentIdEqualTo(documentId);
            List<PaymentPo> list = paymentPoMapper.selectByExample(example);
            if (list.size() == 0) {
                return new ReturnObject(ReturnNo.RESOURCE_ID_NOTEXIST, "支付信息不存在");
            }
            return new ReturnObject(list);
        } catch (Exception e) {
            return new ReturnObject(ReturnNo.INTERNAL_SERVER_ERR, e.getMessage());
        }
    }

}
